import { View, Text } from '@tarojs/components'
import { useState } from 'react'
import { Button, Card, Tag } from '@nutui/nutui-react-taro'
import Taro, { useLoad } from '@tarojs/taro'
import { userApi, orderApi } from '../../api/index'
import errorHandler from '../../utils/errorHandler'
import './index.less'

export default function ErrorDemo() {
  const [logs, setLogs] = useState([])
  const [loading, setLoading] = useState(false)

  useLoad(() => {
    // 获取本地错误日志
    const errorLog = errorHandler.getErrorLog()
    setLogs(errorLog.slice(0, 5)) // 只显示最近5条
  })

  // 模拟网络错误
  const simulateNetworkError = async () => {
    setLoading(true)
    try {
      // 请求一个不存在的接口
      await Taro.request({
        url: 'https://nonexistent-api.com/test',
        method: 'GET'
      })
    } catch (error) {
      console.log('捕获到网络错误:', error)
    } finally {
      setLoading(false)
    }
  }

  // 模拟业务错误
  const simulateBusinessError = async () => {
    setLoading(true)
    try {
      // 模拟登录过期错误
      const mockError = new Error('登录已过期')
      mockError.code = 1001
      throw mockError
    } catch (error) {
      errorHandler.handle(error, { api: 'simulateBusinessError' })
    } finally {
      setLoading(false)
    }
  }

  // 模拟参数验证错误
  const simulateValidationError = async () => {
    setLoading(true)
    try {
      // 创建订单时缺少必要参数
      await orderApi.createOrder({
        // 缺少 serviceType, serviceTime, address
      })
    } catch (error) {
      console.log('捕获到验证错误:', error)
    } finally {
      setLoading(false)
    }
  }

  // 测试正常API调用
  const testNormalApi = async () => {
    setLoading(true)
    try {
      const userData = await userApi.getUserInfo()
      Taro.showToast({
        title: '请求成功',
        icon: 'success'
      })
      console.log('用户数据:', userData)
    } catch (error) {
      console.log('API调用失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 清空错误日志
  const clearErrorLog = () => {
    errorHandler.clearErrorLog()
    setLogs([])
    Taro.showToast({
      title: '日志已清空',
      icon: 'success'
    })
  }

  // 刷新错误日志
  const refreshErrorLog = () => {
    const errorLog = errorHandler.getErrorLog()
    setLogs(errorLog.slice(0, 5))
    Taro.showToast({
      title: '日志已刷新',
      icon: 'success'
    })
  }

  const getErrorLevelColor = (level) => {
    const colors = {
      'LOW': 'default',
      'MEDIUM': 'warning',
      'HIGH': 'danger',
      'CRITICAL': 'danger'
    }
    return colors[level] || 'default'
  }

  const getErrorTypeColor = (type) => {
    const colors = {
      'NETWORK': 'primary',
      'BUSINESS': 'warning',
      'VALIDATION': 'danger',
      'PERMISSION': 'danger',
      'SYSTEM': 'default'
    }
    return colors[type] || 'default'
  }

  return (
    <View className='error-demo-page'>
      <Card className='header-card'>
        <Text className='title'>错误处理演示</Text>
        <Text className='subtitle'>测试统一错误处理机制</Text>
      </Card>

      <Card className='test-buttons-card'>
        <Text className='section-title'>错误测试</Text>
        <View className='test-buttons'>
          <Button
            type='primary'
            size='large'
            loading={loading}
            onClick={testNormalApi}
            className='test-btn'
          >
            正常API调用
          </Button>
          
          <Button
            type='warning'
            size='large'
            loading={loading}
            onClick={simulateNetworkError}
            className='test-btn'
          >
            模拟网络错误
          </Button>
          
          <Button
            type='danger'
            size='large'
            loading={loading}
            onClick={simulateBusinessError}
            className='test-btn'
          >
            模拟业务错误
          </Button>
          
          <Button
            type='danger'
            size='large'
            loading={loading}
            onClick={simulateValidationError}
            className='test-btn'
          >
            模拟验证错误
          </Button>
        </View>
      </Card>

      <Card className='error-log-card'>
        <View className='log-header'>
          <Text className='section-title'>错误日志</Text>
          <View className='log-actions'>
            <Button size='small' onClick={refreshErrorLog}>刷新</Button>
            <Button size='small' type='danger' onClick={clearErrorLog}>清空</Button>
          </View>
        </View>
        
        {logs.length === 0 ? (
          <View className='no-logs'>
            <Text>暂无错误日志</Text>
          </View>
        ) : (
          <View className='error-logs'>
            {logs.map((log, index) => (
              <View key={index} className='error-log-item'>
                <View className='log-header-info'>
                  <View className='log-tags'>
                    <Tag type={getErrorTypeColor(log.type)} size='small'>
                      {log.type}
                    </Tag>
                    <Tag type={getErrorLevelColor(log.level)} size='small'>
                      {log.level}
                    </Tag>
                  </View>
                  <Text className='log-time'>
                    {new Date(log.timestamp).toLocaleString()}
                  </Text>
                </View>
                
                <Text className='log-message'>{log.message}</Text>
                
                {log.code && (
                  <Text className='log-code'>错误码: {log.code}</Text>
                )}
                
                {log.context && Object.keys(log.context).length > 0 && (
                  <View className='log-context'>
                    <Text className='context-title'>上下文:</Text>
                    <Text className='context-content'>
                      {JSON.stringify(log.context, null, 2)}
                    </Text>
                  </View>
                )}
              </View>
            ))}
          </View>
        )}
      </Card>

      <Card className='info-card'>
        <Text className='section-title'>功能说明</Text>
        <View className='info-content'>
          <Text className='info-text'>• 🔄 自动重试机制：网络错误自动重试3次</Text>
          <Text className='info-text'>• 📝 错误日志记录：自动记录所有错误信息</Text>
          <Text className='info-text'>• 🎯 分级错误处理：根据错误级别采用不同处理方式</Text>
          <Text className='info-text'>• 🚨 错误上报：严重错误自动上报到服务器</Text>
          <Text className='info-text'>• 🔐 登录状态管理：自动处理登录过期</Text>
          <Text className='info-text'>• 💾 本地缓存：支持接口数据缓存</Text>
          <Text className='info-text'>• 🚫 重复请求拦截：防止重复请求</Text>
        </View>
      </Card>
    </View>
  )
}